package com.lixin.web.netty;

import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

/**
 * Description: netty工具类
 * Author: <a href="https://github.com/zongzibinbin">abin</a>
 * Date: 2023-04-18
 */

public class NettyUtil {

    public static AttributeKey<Integer> UID = AttributeKey.valueOf("userId");

    public static <T> void setAttr(Channel channel, AttributeKey<T> attributeKey, T data) {
        Attribute<T> attr = channel.attr(attributeKey);
        attr.set(data);
    }

    public static <T> T getAttr(Channel channel, AttributeKey<T> id) {
        return channel.attr(id).get();
    }

    /**
     * 这个api不能在handler中使用，因为handler 中只有到处理层的时候才会去设置uid
     *
     * @return
     */
    public static Integer getUserId() {
        return NettyUtil.getAttr(NettyServerStarter.ctxThreadLocal.get().channel(), NettyUtil.UID);
    }
}
